<?php


namespace catchAdmin\project\controller;

use app\common\business\Question;
use app\common\lib\Redis;
use app\common\lib\ZhyxMongo;
use app\common\model\BaseModel;
use app\common\model\PatientInfo;
use app\Request;
use catchAdmin\project\request\ProjectRequest;
use catcher\base\CatchController;
use catcher\base\CatchRequest;
use catcher\CatchResponse;
use catcher\exceptions\FailedException;
use catcher\exceptions\ValidateFailedException;
use catcher\Utils;
use catchAdmin\permissions\model\Users as UsersModel;
use think\exception\ValidateException;

class Project extends CatchController
{
    private $domain = null;

    public function __construct()
    {
        $this->domain = new \app\common\business\Project();
    }

    public function save(CatchRequest $request): \think\response\Json
    {

        $user = $request->user();
        $postData = $request->post();

        $postData["creator_dept_name"] = $user->userDept->department_name ?? "";

        $postData["creator_name"] = $user->username;
        try {
            validate(ProjectRequest::class)->scene("create")->check($postData);
            //执行数据的写入操作
            $result = $this->domain->createProject($postData);
            return CatchResponse::success($result);
        } catch (ValidateException $exception) {
            throw new ValidateFailedException($exception->getMessage());
        }
    }

    public function update(CatchRequest $request, string $id): \think\response\Json
    {
        //根据id获取信息
        $postData = $request->put();
        if (isset($postData["survey"]) && is_string($postData["survey"])) {
            try {
                $postData["survey"] = json_decode($postData["survey"], true, 512, JSON_THROW_ON_ERROR);
            } catch (\JsonException $e) {
                throw new FailedException("无法解析的survey数据");
            }
        }
        $result = $this->domain->modifyProject($id, $postData);
        if (!$result) {
            throw new FailedException("更新失败");
        }
        return CatchResponse::success([], "更新成功");
    }

    public function index(CatchRequest $catchRequest)
    {
        $result = $this->domain->getList();
        return CatchResponse::paginate($result);
    }

    public function getTreeProjectList(): \think\response\Json
    {
        $result = $this->domain->getProjectTree();
        return CatchResponse::success($result);
    }

    public function delete(CatchRequest $request, $id)
    {
        $projectInfo = $this->domain->DelProject($id);
        return CatchResponse::success([], "success");
    }

    public function read(CatchRequest $request, $id)
    {
        $projectInfo = $this->domain->getProjectInfo($id);
        $patientId = $request->param("his_id", "", "string");
        $followId = $request->param("follow_id", "-1", "string");
    
        $canNext = true;
        $answerId = "";
        if (!empty($projectInfo)) {
            if (isset($followId) && !empty($followId)) {

                $followInfo = (new \app\common\model\Follow())->where([["id", "=", $followId]])->find();
                if(!empty($followInfo) && $followInfo["answer_id"]) {
                    $answerId = $followInfo["answer_id"] ?? "";
                    $canNext = false;
                }else{
                    $key = "projectAndAnswer:" .$id.":".$patientId;
                 
                    if(Redis::getInstance()->redis->exists($key)) {
                        $answer = Redis::getInstance()->redis->get($key);
                        $answerInfo = json_decode($answer, true);
                       
                        $answerId = $answerInfo["answer_id"];
                        $canNext = false;
                    }
                }
            }

            $projectInfo["can_next"] = $canNext;
            $projectInfo["answer_id"] = $answerId;

            return CatchResponse::success($projectInfo);
        }
    }

    public function getProjectInfo(Request $request, $id)
    {
        $projectInfo = $this->domain->getProjectInfo($id);
        if (empty($projectInfo)) {
            throw new FailedException("问卷不存在");
        }
        return CatchResponse::success($projectInfo);
    }

    public function getSatisfactionNodeByPoint(CatchRequest $request): \think\response\Json
    {
        $condition = [];
        $personType = $request->param("personnel_type", 1, "int");
        $condition[] = ["personnelType", "=", $personType];
        $point = $request->param("point", 0, "int");
        if (!empty($point)) {
            $condition[] = ["point", "=", $point];
        }
        $result = $this->domain->getProjectByCondition($condition);
        return CatchResponse::success($result);
    }

    public function getChronicDiseaseEvaluationList(CatchRequest $request): \think\response\Json
    {
        $condition = [];
        $condition[] = ["survey_type", "=", 3];
        $point = $request->param("estimate_type", 0, "int");
        if (!empty($point)) {
            $condition[] = ["estimateType", "=", $point];
        }
        $result = $this->domain->getProjectByCondition($condition);
        return CatchResponse::success($result);
    }

    public function getProjectByDept(CatchRequest $request): \think\response\Json
    {
        $createDate = $request->param("date", []);
        if (empty($createDate)) {
            $createDate = [mktime(0, 0, 0, 1, 1, date("Y")), time()];

        } else {
            $createDate[0] = strtotime($createDate[0]);
            $createDate[1] = strtotime($createDate[1] . " 23:59:59");
        }
        $match = ['created_at' => ['$gte' => $createDate[0], '$lte' => $createDate[1]], 'deleted_at' => 0, 'questions.classification' => 2];

        $deptId = $request->param("dept_id", "", "string");
        if (!empty(trim($deptId))) {
            $match['patientDeptId'] = (string)$deptId;
        } else {
            #获取部门权限集合
            if (!Utils::isSuperAdmin()) {
                $deptIds = (new BaseModel())->getDeptListByUser([]);
                if (!empty($deptIds)) {
                    foreach ($deptIds as $k => &$v) {
                        $v = (string)$v;
                    }
                    $match["patientDeptId"] = ['$in' => $deptIds];
                }
            }
        }
        $collection = ZhyxMongo::getInstance()->setCollection('answer');
        $cursor = $collection->aggregate([['$match' => $match], ['$group' => ['_id' => '$questions.projectId', 'name' => ['$first' => '$questions.name'], 'project_uuid' => ['$first' => '$questions.id']]], ['$project' => ['projectId' => '$_id', 'name' => true, 'project_uuid' => true, '_id' => false]]]);
        return CatchResponse::success(iterator_to_array($cursor));
    }


    public function satisfactionProjectReport(CatchRequest $request): \think\response\Json
    {
        $createDate = $request->param("date", []);
        if (empty($createDate)) {
            $createDate = [mktime(0, 0, 0, 1, 1, date("Y")), time()];

        } else {
            $createDate[0] = strtotime($createDate[0]);
            $createDate[1] = strtotime($createDate[1] . " 23:59:59");
        }
        $match = ['created_at' => ['$gte' => $createDate[0], '$lte' => $createDate[1]], 'deleted_at' => 0, 'questions.personnelType' => ['$lt' => 3]];
        $deptId = $request->param("dept_id", "", "int");
        if ($deptId > 0) {
            $match['creator_dept_id'] = $deptId;
        } else {
            #获取部门权限集合
            if (!Utils::isSuperAdmin()) {
                $deptIds = (new BaseModel())->getDeptListByUser([]);
                if (!empty($deptIds)) {
                    $match["creator_dept_id"] = ['$in' => $deptIds];
                }
            }
        }
        $collection = ZhyxMongo::getInstance()->setCollection('answer');
        $cursor = $collection->aggregate([['$match' => $match], ['$group' => ['_id' => '$questions.projectId', 'dept_name' => ['$first' => '$creator_dept_name'], 'creator_name' => ['$first' => '$creator_name'], 'name' => ['$first' => '$questions.name'], 'project_uuid' => ['$first' => '$questions.id'], 'projectId' => ['$first' => '$questions.id']]], ['$project' => ['projectId' => '$_id', 'name' => true, 'project_uuid' => true, '_id' => false, 'dept_name' => true, 'creator_name' => true]]]);
        return CatchResponse::success(iterator_to_array($cursor));
    }

    public function getProjectListByDeptId(CatchRequest $request): \think\response\Json
    {

        $deptId = $request->param("dept_id", "", "int");
        $followId = $request->param("follow_id", "", "string");
        $patientId = $request->param("patientId", "", "string");

        if (empty($deptId) || $deptId <= 0) {
            throw new ValidateFailedException("科室id不能为空");
        }
        $key = "projectAndAnswer:".$patientId;
        $projectId = Redis::getInstance()->redis->get($key);
        if ($projectId) {
            $project = json_decode($projectId, true, 512, JSON_THROW_ON_ERROR);
            $projectList = $this->domain->getProjectByCondition([["projectId", "=", $project['projectId']]]);
        }else{
            $projectList = $this->domain->getProjectByCondition([["dept_list.dept_id", "=", $deptId]]);
        }

        return CatchResponse::success($projectList);
    }


}